﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Blue.ResourceManager;
using System.IO;
using System.Xml;
using EngineOfEvermore.Imaging;
using EngineOfEvermore.Common;
using System.Diagnostics;

namespace EngineOfEvermore.Imaging
{
    public sealed class FrameAnimationException : Exception
    {
        public enum Reason
        {
            NO_IMAGEMAP,
            NO_FRAMES,
            INVALID_FRAME_TIME,
            INVALID_IMAGEMAP_FRAME_INDEX
        }

        public readonly Reason ExceptionReason;

        public FrameAnimationException( String message, Reason reason ) :
            base( message )
        {
            ExceptionReason = reason;
        }
    }

    public struct AnimationSubFrame
    {
        public AnimationSubFrame( ImageMap imageMap, int imageMapFrameIndex, Vector2d offset )
        {
            ImageMap = imageMap;
            ImageMapFrameIndex = imageMapFrameIndex;
            Offset = offset;
        }

        public ImageMap ImageMap;
        public int ImageMapFrameIndex;
        public Vector2d Offset;
    }

    public sealed class AnimationFrame
    {
        readonly float _duration;
        readonly AnimationSubFrame[] _subFrames;

        public sealed class Builder
        {
            public float Duration;
            public readonly List<AnimationSubFrame> SubFrames = new List<AnimationSubFrame>();

            public AnimationFrame Create()
            {
                return new AnimationFrame( Duration, SubFrames );
            }
        }

        public AnimationFrame( float duration, IEnumerable<AnimationSubFrame> subFrames )
        {
            _duration = duration;
            _subFrames = subFrames.ToArray();
        }

        public AnimationFrame( float duration, AnimationSubFrame singleSubFrame ):
            this( duration, new AnimationSubFrame[] { singleSubFrame } )
        {
        }

        public float Duration
        {
            get { return _duration; }
        }

        public int SubFrameCount
        {
            get { return _subFrames.Length; }
        }

        public IEnumerable<AnimationSubFrame> SubFrames
        {
            get { return _subFrames; }
        }

        public AnimationSubFrame this[int index]
        {
            get { return _subFrames[index]; }
        }

        public AnimationFrame Clone()
        {
            return new AnimationFrame( _duration, _subFrames );
        }
    }

    public class EdibleFrameAnimation
    {
        #region Constants
        const String XMLNS = "http://engineofevermore.wordpress.com/EngineOfEvermore.xsd";
        #endregion

        #region Iterator struct
        public struct Iterator
        {
            public Iterator( EdibleFrameAnimation animation )
            {
                _animation = animation;
                _frameIndex = 0;
                _frameOffset = 0.0f;
            }

            EdibleFrameAnimation _animation;
            int _frameIndex;
            float _frameOffset;

            public int FrameIndex
            {
                get { return _frameIndex; }
            }

            public EdibleFrameAnimation Animation
            {
                get { return _animation; }
            }

            public float CurrentTime
            {
                get
                {
                    float time = 0.0f;

                    for ( int i = 0; i < _frameIndex; ++i )
                    {
                        time += _animation._frames[_frameIndex].Duration;
                    }

                    return time + _frameOffset;
                }
            }

            public int Advance( float dt )
            {
                if ( _animation == null || _animation.FrameCount <= 0 )
                    return -1;

                float timeLeftInThisFrame =
                    _animation._frames[_frameIndex].Duration - _frameOffset;

                if ( dt < timeLeftInThisFrame )
                {
                    _frameOffset += dt;
                }
                else
                {
                    while ( dt > timeLeftInThisFrame )
                    {
                        dt -= timeLeftInThisFrame;
                        ++_frameIndex;

                        if ( _frameIndex >= _animation._frames.Count )
                        {
                            if ( _animation._isLooped )
                            {
                                _frameIndex = 0;
                            }
                            else
                            {
                                _frameIndex = _animation._frames.Count - 1;
                                return _frameIndex;
                            }
                        }

                        timeLeftInThisFrame = _animation._frames[_frameIndex].Duration;
                    }

                    _frameOffset = dt;
                }
                
                return _frameIndex;
            }
        }
        #endregion

        #region Variables
        List<AnimationFrame> _frames = new List<AnimationFrame>();
        float _totalDuration;
        bool _isLooped;
        static XmlWriterSettings _xmlWriterSettings;
        static XmlReaderSettings _xmlReaderSettings;
        readonly static char[] _splitCharacters = { ' ' };
        #endregion

        #region Properties
        public bool IsLooped
        {
            get { return _isLooped; }
            set { _isLooped = value; }
        }

        public int FrameCount
        {
            get { return _frames.Count; }
        }

        public AnimationFrame this[int index]
        {
            get { return _frames[index]; }
        }

        public float Duration
        {
            get { return _totalDuration; }
        }
        #endregion

        #region Public Methods
        public Iterator GetIterator()
        {
            return new Iterator( this );
        }

        public void AppendFrame( AnimationFrame frame )
        {
            _frames.Add( frame );
            _updateTotalDuration();
        }

        public void DeleteFrame( int animationFrameIndex )
        {
            _frames.RemoveAt( animationFrameIndex );
            _updateTotalDuration();
        }

        public void MoveFrame( int oldIndex, int newIndex )
        {
            AnimationFrame frame = _frames[oldIndex];

            _frames.RemoveAt( oldIndex );
            _frames.Insert( newIndex, frame );
            _updateTotalDuration();
        }

        public void SetFrame( int index, AnimationFrame frame )
        {
            _frames[index] = frame;
            _updateTotalDuration();
        }

        public void InsertFrame( int index, AnimationFrame frame )
        {
            _frames.Insert( index, frame );
            _updateTotalDuration();
        }

        public void Validate()
        {
            if ( _frames.Count == 0 )
            {
                throw new FrameAnimationException(
                    "The Animation has no frames",
                    FrameAnimationException.Reason.NO_FRAMES
                    );
            }

            for ( int i = 0; i < _frames.Count; ++i )
            {
                AnimationFrame frame = _frames[i];

                if ( frame.Duration < Util.STANDARD_EPSILON )
                {
                    throw new FrameAnimationException(
                        "Frame " + i + " has the invalid frame duration " + frame.Duration,
                        FrameAnimationException.Reason.INVALID_FRAME_TIME
                        );
                }

                for ( int j = 0; j < frame.SubFrameCount; ++j )
                {
                    AnimationSubFrame subFrame = frame[j];

                    ImageMap imageMap = subFrame.ImageMap;

                    if ( imageMap == null )
                    {
                        throw new FrameAnimationException(
                            "SubFrame " + j + " of Frame " + i + " references no imageMap",
                            FrameAnimationException.Reason.NO_IMAGEMAP
                            );
                    }

                    if ( subFrame.ImageMapFrameIndex >= imageMap.FrameCount ||
                         subFrame.ImageMapFrameIndex < 0 )
                    {
                        throw new FrameAnimationException(
                            "SubFrame " + j + " of Frame " + i + 
                            " has the invalid ImageMapFrameIndex " + subFrame.ImageMapFrameIndex,
                            FrameAnimationException.Reason.INVALID_FRAME_TIME
                            );
                    }
                }
            }
        }

        public void SaveToXmlStream( Stream stream )
        {
            StringBuilder stringBuilder = new StringBuilder();
            XmlWriter writer = XmlWriter.Create( stream, _xmlWriterSettings );
            
            writer.WriteStartElement( "FrameAnimation", XMLNS );
            
            writer.WriteElementString( "IsLooped", _isLooped.ToString() );

            writer.WriteStartElement( "Frames" );

            foreach ( AnimationFrame frame in _frames )
            {
                writer.WriteStartElement( "Frame" );

                writer.WriteElementString( "Duration",
                    frame.Duration.ToString( 
                        System.Globalization.NumberFormatInfo.InvariantInfo ) );

                writer.WriteStartElement( "SubFrames" );

                foreach ( AnimationSubFrame subFrame in frame.SubFrames )
                {
                    writer.WriteStartElement( "SubFrame" );

                    writer.WriteElementString( "ImageMap", subFrame.ImageMap.ResourceName );

                    writer.WriteElementString( "ImageMapFrameIndex", 
                        subFrame.ImageMapFrameIndex.ToString() );

                    stringBuilder.Length = 0;
                    stringBuilder.AppendFormat(
                        System.Globalization.NumberFormatInfo.InvariantInfo,
                        "{0:G} {1:G}", subFrame.Offset.X, subFrame.Offset.Y
                        );

                    writer.WriteElementString( "Offset", stringBuilder.ToString() );

                    writer.WriteEndElement(); // SubFrame
                }

                writer.WriteEndElement(); // SubFrames

                writer.WriteEndElement(); // Frame
            }

            writer.WriteEndElement(); // Frames
            writer.WriteEndElement(); // FrameAnimation

            writer.Close();
        }

        public EdibleFrameAnimation Clone()
        {
            EdibleFrameAnimation clone = new EdibleFrameAnimation();
            clone._isLooped = _isLooped;
            clone._totalDuration = _totalDuration;

            foreach ( AnimationFrame frame in _frames )
            {
                clone._frames.Add( frame.Clone() );
            }

            return clone;
        }
        #endregion

        #region Static Methods
        public static EdibleFrameAnimation LoadFromXmlStream( Stream stream )
        {
            EdibleFrameAnimation animation = new EdibleFrameAnimation();

            XmlReader reader = XmlReader.Create( stream, _xmlReaderSettings );

            try
            {
                reader.ReadStartElement( "FrameAnimation", XMLNS );

                animation.IsLooped =
                    bool.Parse( reader.ReadElementString( "IsLooped", XMLNS ) );

                reader.ReadStartElement( "Frames", XMLNS );

                while ( reader.IsStartElement( "Frame", XMLNS ) )
                {
                    reader.ReadStartElement();

                    AnimationFrame.Builder frame = new AnimationFrame.Builder();

                    frame.Duration = float.Parse(
                        reader.ReadElementString( "Duration", XMLNS ), 
                        System.Globalization.NumberFormatInfo.InvariantInfo
                        );

                    reader.ReadStartElement( "SubFrames", XMLNS );

                    while ( reader.IsStartElement( "SubFrame", XMLNS ) )
                    {
                        reader.ReadStartElement(); // SubFrame

                        AnimationSubFrame subFrame = new AnimationSubFrame();

                        String imageMapName = reader.ReadElementString( "ImageMap", XMLNS );
                        subFrame.ImageMap = ResourceManager.GetResource<ImageMap>( imageMapName );

                        subFrame.ImageMapFrameIndex =
                            int.Parse( reader.ReadElementString( "ImageMapFrameIndex", XMLNS ),
                            System.Globalization.NumberFormatInfo.InvariantInfo 
                            );

                        String offsetString = reader.ReadElementString( "Offset", XMLNS );
                        String[] elements = offsetString.Split( _splitCharacters, 2 );

                        Debug.Assert( elements.Length == 2 );

                        subFrame.Offset.X = float.Parse( elements[0], 
                            System.Globalization.NumberFormatInfo.InvariantInfo );

                        subFrame.Offset.Y = float.Parse( elements[1],
                            System.Globalization.NumberFormatInfo.InvariantInfo );

                        frame.SubFrames.Add( subFrame );

                        reader.ReadEndElement(); // SubFrame
                    }

                    reader.ReadEndElement(); // SubFrames

                    reader.ReadEndElement(); // Frame

                    animation.AppendFrame( frame.Create() );
                }

                reader.ReadEndElement(); // Frames
                reader.ReadEndElement(); // FrameAnimation
            }
            finally
            {
                reader.Close();
            }

            return animation;
        }

        internal static void SetXmlSchema( String resourceName )
        {
            var schemaResource = ResourceManager.GetResource<XmlSchemaResource>( resourceName );

            System.Xml.Schema.XmlSchemaSet schemaSet = new System.Xml.Schema.XmlSchemaSet();
            schemaSet.Add( schemaResource.Schema );

            _xmlReaderSettings.Schemas = schemaSet;
        }

        static EdibleFrameAnimation()
        {
            _xmlWriterSettings = new XmlWriterSettings();
            _xmlWriterSettings.CloseOutput = false;
            _xmlWriterSettings.Encoding = Encoding.UTF8;
            _xmlWriterSettings.Indent = true;

            _xmlReaderSettings = new XmlReaderSettings();
            _xmlReaderSettings.CloseInput = false;
            _xmlReaderSettings.IgnoreComments = true;
            _xmlReaderSettings.IgnoreProcessingInstructions = true;
        }
        #endregion

        #region Private Methods
        void _updateTotalDuration()
        {
            _totalDuration = 0.0f;

            foreach ( AnimationFrame frame in _frames )
            {
                _totalDuration += frame.Duration;
            }
        }
        #endregion
    }

    public class FrameAnimation : Resource
    {
        #region Iterator struct
        public struct Iterator
        {
            public Iterator( FrameAnimation animation )
            {
                _animation = animation;
                _wrappedIterator = _animation._wrappedAnimation.GetIterator();
            }

            EdibleFrameAnimation.Iterator _wrappedIterator;
            FrameAnimation _animation;

            public int FrameIndex
            {
                get { return _wrappedIterator.FrameIndex; }
            }

            public FrameAnimation Animation
            {
                get { return _animation; }
            }

            public int Advance( float time )
            {
                return _wrappedIterator.Advance( time );
            }

            public readonly static Iterator Empty = new Iterator();
        }

        #endregion

        #region Variables
        EdibleFrameAnimation _wrappedAnimation;
        #endregion

        #region Constructor (private)
        FrameAnimation( String resourceName, 
            EdibleFrameAnimation wrappedAnimation ):
            base( resourceName )
        {
            _wrappedAnimation = wrappedAnimation;
        }
        #endregion

        #region Properties
        public bool IsLooped
        {
            get { return _wrappedAnimation.IsLooped; }
        }

        public int FrameCount
        {
            get { return _wrappedAnimation.FrameCount; }
        }

        public AnimationFrame this[int index]
        {
            get { return _wrappedAnimation[index]; }
        }

        public float Duration
        {
            get { return _wrappedAnimation.Duration; }
        }
        #endregion

        #region Methods
        public Iterator GetIterator()
        {
            return new Iterator( this );
        }

        public static Resource LoadResource( String resourceName, Stream stream )
        {
            EdibleFrameAnimation animation =
                EdibleFrameAnimation.LoadFromXmlStream( stream );

            return new FrameAnimation( resourceName, animation );
        }

        public static FrameAnimation CreateEdibleAnimationWrapper( EdibleFrameAnimation a )
        {
            return new FrameAnimation( null, a );
        }

        public EdibleFrameAnimation CreateEdibleFrameAnimation()
        {
            return _wrappedAnimation.Clone();
        }
        #endregion
    }
}
